from django import template
register = template.Library()   # 注册器


@register.inclusion_tag('student/paginator.html', takes_context=True)
def pagination_html(context):
    total_sts = context['total_sts']
    total_page = context['total_page']
    page = context['page']
    per_page = context['per_page']
    page_list = context['p'].page_range

    page_list = []
    num = 1  # 控制选中的页码的左右边显示的页数
    if page <= num:                            # 当左边不够显示时,
        for i in range(1, page+1):             # 包含了当前页码
            page_list.append(i)
    else:
        for i in range(page-num, page+1):      # 选择页码的左边加上当前页码，当前页码后边的在下面配置
            page_list.append(i)
    if page + num >= total_page:               # 当右边不够显示时
        for i in range(page+1, total_page+1):  # 不包含当前页码左边和当前页码，所以从当前页码加一开始，最大页码结束
            page_list.append(i)
    else:
        for i in range(page+1, page+num+1):    # 右边够，所以结束页码和最大页码没关系，根据我们设置的num来
            page_list.append(i)

    return {'total_sts': total_sts,
            'page': page,
            'per_page': per_page,
            'page_list': page_list,
            'total_page': total_page
            }


@register.simple_tag()
def add_class(filed, class_str):
    return filed.as_widget(attrs={'class': class_str})
